﻿using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Threading.Tasks;
using WebApplication3.Data;
using WebApplication3.Model;


namespace WebApplication3.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class RegisterController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public RegisterController(ApplicationDbContext context)
        {
            _context = context;
        }

        [HttpPost("register")]
        public async Task<IActionResult> Register([FromBody] RegisterRequest request)
        {
            if (request == null || string.IsNullOrEmpty(request.UserId) || string.IsNullOrEmpty(request.Password))
            {
                return BadRequest(new { code = 400, message = "Invalid request." });
            }

            var existingUser = _context.User.FirstOrDefault(u => u.UserId == request.UserId);
            if (existingUser != null)
            {
                return Conflict(new { code = 409, message = "Username already exists." });
            }

            var user = new User
            {
                UserId = request.UserId,
                Password = request.Password,
                Id = request.Id,
                Username = request.Username
            };

            _context.User.Add(user);
            await _context.SaveChangesAsync();

            return Ok(new
            {
                code = 200,
                message = "User registered successfully.",
                data = new
                {
                    id = user.Id,
                    username = user.Username
                }
            });
        }

        public class RegisterRequest
        {
            public string UserId { get; set; }
            public string Password { get; set; }
            public int Id { get; set; }
            public string Username { get; set; }
        }
    }
}
